<template>
  <div class="shipments-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="通知单编号">
          <el-input v-model="searchForm.shipmentsCode" placeholder="请输入通知单编号"></el-input>
        </el-form-item>
        <el-form-item label="通知单名称">
          <el-input v-model="searchForm.shipmentsName" placeholder="请输入通知单名称"></el-input>
        </el-form-item>
        <el-form-item label="销售订单编号">
          <el-input v-model="searchForm.saleCode" placeholder="请输入销售订单编号"></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.custName" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="客户简称">
          <el-input v-model="searchForm.custAbbreviation" placeholder="请输入客户简称"></el-input>
        </el-form-item>
        <el-form-item label="客户编码">
          <el-input v-model="searchForm.custCode" placeholder="请输入客户编码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operations">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增
      </el-button>
      <el-button 
        type="success" 
        :disabled="!selectedRows.length || selectedRows.length > 1"
        @click="handleEdit(selectedRows[0])"
      >
        <el-icon><Edit /></el-icon> 修改
      </el-button>
      <el-button 
        type="danger" 
        :disabled="!selectedRows.length"
        @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon> 批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      v-loading="loading"
      @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="shipmentsCode" label="通知单编号" min-width="150" show-overflow-tooltip />
      <el-table-column prop="shipmentsName" label="通知单名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="saleCode" label="销售订单编号" min-width="150" show-overflow-tooltip />
      <el-table-column prop="custName" label="客户名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="shipmentsTime" label="发货日期" min-width="150" show-overflow-tooltip>
        <template #default="scope">
          {{ formatDate(scope.row.shipmentsTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="receivingName" label="收货人" min-width="120" show-overflow-tooltip />
      <el-table-column prop="phone" label="联系方式" min-width="120" show-overflow-tooltip />
      <el-table-column prop="receivingAddress" label="收货地址" min-width="200" show-overflow-tooltip />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button 
              type="primary" 
              link 
              size="small" 
              @click="handleEdit(scope.row)"
              :disabled="scope.row.state !== 0"
            >
              修改
            </el-button>
            <el-button 
              type="danger" 
              link 
              size="small" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.state !== 0"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <div class="pagination-info">
        共 {{ pagination.total }} 条
      </div>
      <div class="pagination-select">
        <span>{{ pagination.pageSize }}条/页</span>
        <el-dropdown @command="handleSizeChange">
          <el-button type="text">
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="size in pagination.pageSizes" :key="size" :command="size">
                {{ size }}条/页
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <el-pagination
        v-model:current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="prev, pager, next, jumper"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.id ? '修改发货通知单' : '新增发货通知单'"
      width="60%"
      :close-on-click-modal="false"
      @close="handleEditDialogClose"
      :destroy-on-close="true"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
        class="shipment-form"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="通知单编号" prop="shipmentsCode" required>
              <div class="code-input-container">
                <el-input 
                  v-model="editForm.shipmentsCode" 
                  placeholder="请输入通知单编号"
                  :disabled="!!editForm.id"
                />
                <el-switch 
                  v-if="!editForm.id"
                  v-model="autoGenerate" 
                  class="auto-switch"
                  active-text="自动生成"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="通知单名称" prop="shipmentsName" required>
              <el-input 
                v-model="editForm.shipmentsName" 
                placeholder="请输入通知单名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="销售订单编号" prop="saleCode">
              <el-input 
                v-model="editForm.saleCode" 
                placeholder="请输入销售订单编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户编码" prop="custCode" required>
              <div class="customer-input-container">
                <el-input 
                  v-model="editForm.custCode" 
                  placeholder="请选择客户"
                  readonly
                />
                <el-button 
                  class="select-customer-btn"
                  @click="openCustomerSelect"
                >
                  <el-icon><Search /></el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input 
                v-model="editForm.custName" 
                placeholder="客户名称"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="发货日期" prop="shipmentsTime" required>
              <el-date-picker
                v-model="editForm.shipmentsTime"
                type="datetime"
                placeholder="请选择发货日期"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货人" prop="receivingName" required>
              <el-input 
                v-model="editForm.receivingName" 
                placeholder="请输入收货人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式" prop="phone" required>
              <el-input 
                v-model="editForm.phone" 
                placeholder="请输入联系方式"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="收货地址" prop="receivingAddress" required>
          <el-input 
            v-model="editForm.receivingAddress" 
            placeholder="请输入收货地址"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="editForm.speak"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>

      <!-- 物料信息部分 -->
      <div class="material-section">
        <div class="material-header">
          <div class="title">物料信息</div>
          <div class="material-toolbar">
            <el-button type="primary" plain @click="handleAddMaterial">
              <el-icon><Plus /></el-icon> 新增
            </el-button>
            <el-button type="success" plain @click="handleEditMaterial">
              <el-icon><Edit /></el-icon> 修改
            </el-button>
            <el-button type="danger" plain @click="handleBatchDeleteMaterial">
              <el-icon><Delete /></el-icon> 批量删除
            </el-button>
          </div>
        </div>

        <el-table
          ref="materialTableRef"
          :data="materialTableData"
          border
          style="width: 100%"
          @selection-change="handleMaterialSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="materialCode" label="物料编码" min-width="150" />
          <el-table-column prop="materialName" label="物料名称" min-width="120" />
          <el-table-column prop="specification" label="规格型号" min-width="120" />
          <el-table-column prop="flats" label="单位" width="100" />
          <el-table-column prop="flatsMaterial" label="物料产品分类" min-width="120" />
          <el-table-column label="是否启用" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.isLock"
                :active-value="1"
                :inactive-value="0"
                @change="handleEnableChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="安全库存" width="100" align="center">
            <template #default="scope">
              <el-tag
                :type="scope.row.safetyStock === 1 ? 'success' : 'info'"
                effect="plain"
              >
                {{ scope.row.safetyStock === 1 ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="descs" label="备注" min-width="150" show-overflow-tooltip />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button 
                link 
                type="primary" 
                size="small" 
                @click="handleEditMaterial(scope.row)"
                :disabled="scope.row.isLock === 1"
              >
                修改
              </el-button>
              <el-button 
                link 
                type="danger" 
                size="small" 
                @click="handleDeleteMaterial(scope.row)"
                :disabled="scope.row.isLock === 1"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="materialPagination.currentPage"
            v-model:page-size="materialPagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="materialPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleMaterialSizeChange"
            @current-change="handleMaterialCurrentChange"
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSave">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物料编辑对话框 -->
    <el-dialog
      v-model="materialDialogVisible"
      :title="materialForm.id ? '修改物料' : '新增物料'"
      width="50%"
      :close-on-click-modal="false"
      @close="materialDialogVisible = false"
    >
      <el-form
        ref="materialFormRef"
        :model="materialForm"
        :rules="materialRules"
        label-width="100px"
      >
        <el-form-item label="物料编码" prop="materialCode">
          <div class="material-input-container">
            <el-input v-model="materialForm.materialCode" placeholder="请输入物料编码" />
            <el-button 
              class="select-material-btn"
              @click="openMaterialSelect"
            >
              <el-icon><Search /></el-icon>
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="materialForm.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="materialForm.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="单位" prop="flats">
          <el-input v-model="materialForm.flats" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="物料分类" prop="flatsMaterial">
          <el-input v-model="materialForm.flatsMaterial" placeholder="请输入物料分类" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="materialForm.isLock" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="安全库存">
          <el-input v-model="materialForm.safetyStock" placeholder="请输入安全库存" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="materialForm.descs"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="materialDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveMaterial">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 客户选择对话框 -->
    <customer-select
      v-model:visible="customerSelectVisible"
      @select="handleCustomerSelect"
    />

    <!-- 物料选择对话框 -->
    <material-select
      v-model:visible="materialSelectVisible"
      @select="handleMaterialSelect"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, ArrowDown, Grid } from '@element-plus/icons-vue'
import http from '@/api/http'
import CustomerSelect from './components/CustomerSelect.vue'
import MaterialSelect from './components/MaterialSelect.vue'

// 页面状态
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  shipmentsCode: '',
  shipmentsName: '',
  saleCode: '',
  custCode: '',
  custName: '',
  custAbbreviation: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 30, 50]
})

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const autoGenerate = ref(true)
const customerSelectVisible = ref(false)

// 编辑表单
const editForm = reactive({
  id: '',
  shipmentsCode: '',
  shipmentsName: '',
  saleCode: '',
  custCode: '',
  custName: '',
  shipmentsTime: '',
  receivingName: '',
  phone: '',
  receivingAddress: '',
  speak: '',
  state: 0
})

// 表单验证规则
const rules = {
  shipmentsName: [{ required: true, message: '请输入通知单名称', trigger: 'blur' }],
  custCode: [{ required: true, message: '请选择客户', trigger: 'change' }],
  shipmentsTime: [{ required: true, message: '请选择发货日期', trigger: 'change' }],
  receivingName: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  receivingAddress: [{ required: true, message: '请输入收货地址', trigger: 'blur' }]
}

// 物料表格相关数据
const materialTableRef = ref(null)
const materialTableData = ref([])
const selectedMaterials = ref([])
const materialPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 物料编辑对话框
const materialDialogVisible = ref(false)
const materialFormRef = ref(null)
const materialForm = reactive({
  id: '',
  materialCode: '',
  materialName: '',
  specification: '',
  flats: '',
  flatsMaterial: '',
  isLock: 0,
  safetyStock: 0,
  descs: ''
})

// 物料表单验证规则
const materialRules = {
  materialCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  specification: [{ required: true, message: '请输入规格型号', trigger: 'blur' }],
  flats: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  flatsMaterial: [{ required: true, message: '请输入物料分类', trigger: 'blur' }],
  isLock: [{ required: true, message: '请选择是否启用', trigger: 'change' }],
  safetyStock: [{ required: true, message: '请输入安全库存', trigger: 'blur' }]
}

// 物料选择对话框
const materialSelectVisible = ref(false)

// 获取物料列表
const getMaterialList = async () => {
  try {
    loading.value = true
    
    // 构造请求参数
    const params = {
      pageIndex: 1,
      pageSize: 999
    }

    console.log('开始请求物料列表...')
    console.log('请求参数:', params)

    const res = await http.get('/api/MaterialProduct/GetMaterialProduct', params, true)
    
    console.log('API响应结果:', res)

    if (res && res.status === true) {
      // 从 data.products 中获取物料数据
      if (res.data && res.data.products) {
        materialTableData.value = res.data.products
        materialPagination.total = res.data.totalCount || res.data.products.length
        
        // 转换数据字段名称为小写，以匹配表格的 prop
        materialTableData.value = materialTableData.value.map(item => ({
          id: item.id,
          materialCode: item.materialCode,
          materialName: item.materialName,
          specification: item.specification,
          flats: item.flats,
          flatsMaterial: item.flatsMaterial,
          isLock: item.isLock || 0,
          safetyStock: Number(item.safetyStock || 0),
          descs: item.descs || ''
        }))
        
        console.log('处理后的物料数据:', materialTableData.value)
        console.log('数据总数:', materialPagination.total)
      } else {
        console.warn('API返回数据中没有 products 数组')
        materialTableData.value = []
        materialPagination.total = 0
      }
    } else {
      console.error('API返回错误:', res?.message)
      materialTableData.value = []
      materialPagination.total = 0
      ElMessage.error(res?.message || '获取物料数据失败')
    }
  } catch (error) {
    console.error('获取物料列表失败:', error)
    materialTableData.value = []
    materialPagination.total = 0
    ElMessage.error('获取物料数据失败')
  } finally {
    loading.value = false
  }
}

// 处理物料选择变化
const handleMaterialSelectionChange = (selection) => {
  selectedMaterials.value = selection
}

// 处理物料分页大小变化
const handleMaterialSizeChange = (val) => {
  materialPagination.pageSize = val
  getMaterialList()
}

// 处理物料当前页变化
const handleMaterialCurrentChange = (val) => {
  materialPagination.currentPage = val
  getMaterialList()
}

// 处理启用状态变化
const handleEnableChange = async (row) => {
  try {
    // 构造更新的数据，确保字段名称与数据库一致
    const updateData = {
      Id: row.id,
      MaterialCode: row.materialCode,
      MaterialName: row.materialName,
      Specification: row.specification,
      Flats: row.flats,
      FlatsMaterial: row.flatsMaterial,
      IsLock: row.isLock ? 1 : 0,
      SafetyStock: row.safetyStock || '',
      Descs: row.descs || ''
    }

    console.log('更新物料数据:', updateData)

    const res = await http.post('/api/MaterialProduct/UpdateMaterialProduct', updateData)
    if (res.status === true) {
      ElMessage.success('更新成功')
      getMaterialList()
    } else {
      ElMessage.error(res.message || '更新失败')
      row.isLock = !row.isLock // 恢复状态
    }
  } catch (error) {
    console.error('更新启用状态失败:', error)
    ElMessage.error('更新失败')
    row.isLock = !row.isLock // 恢复状态
  }
}

// 处理添加物料
const handleAddMaterial = () => {
  // 打开物料添加对话框
  materialDialogVisible.value = true
  // 重置表单数据
  Object.assign(materialForm, {
    id: '',
    materialCode: '',
    materialName: '',
    specification: '',
    flats: '',
    flatsMaterial: '',
    isLock: 0,
    safetyStock: 0,
    descs: ''
  })
}

// 处理编辑物料
const handleEditMaterial = (row) => {
  materialDialogVisible.value = true
  // 复制数据到表单
  Object.assign(materialForm, { ...row })
}

// 处理删除物料
const handleDeleteMaterial = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该物料吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    const res = await http.get(`/api/MaterialProduct/DeleteMaterialProduct?id=${row.id}`)
    
    if (res.status === true) {
      ElMessage.success('删除成功')
      getMaterialList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除物料失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 监听编辑对话框打开
watch(editDialogVisible, (val) => {
  if (val) {
    console.log('编辑对话框打开，开始获取物料列表...')
    getMaterialList()
  }
})

// 获取列表数据
const getShipmentsList = async () => {
  loading.value = true
  try {
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      shipmentsCode: searchForm.shipmentsCode || '',
      shipmentsName: searchForm.shipmentsName || '',
      saleCode: searchForm.saleCode || '',
      custCode: searchForm.custCode || '',
      custName: searchForm.custName || '',
      custAbbreviation: searchForm.custAbbreviation || ''
    }
    const res = await http.get('/api/ShipmentsModel/QueryShipmentsModelList', params)
    if (res.status === true) {
      tableData.value = res.data.items || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getShipmentsList()
}

// 处理重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  handleSearch()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getShipmentsList()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理添加按钮点击
const handleAdd = () => {
  handleEditDialogClose() // 清空表单
  if (autoGenerate.value) {
    generateShipmentsCode()
  }
  editDialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  if (!row) {
    ElMessage.warning('请选择要编辑的记录')
    return
  }
  
  try {
    console.log('开始编辑数据:', row)
    handleEditDialogClose() // 清空表单
    
    // 确保所有必要的字段都存在
    const editData = {
      id: row.id || '',
      shipmentsCode: row.shipmentsCode || '',
      shipmentsName: row.shipmentsName || '',
      saleCode: row.saleCode || '',
      custCode: row.custCode || '',
      custName: row.custName || '',
      shipmentsTime: row.shipmentsTime ? row.shipmentsTime.split('.')[0] : '',
      receivingName: row.receivingName || '',
      phone: row.phone || '',
      receivingAddress: row.receivingAddress || '',
      speak: row.speak || '',
      state: row.state || 0
    }
    
    console.log('处理后的编辑数据:', editData)
    
    // 使用 Object.assign 更新表单数据
    Object.assign(editForm, editData)
    
    // 设置自动生成为 false，因为是编辑现有记录
    autoGenerate.value = false
    
    // 打开编辑对话框
    editDialogVisible.value = true
    
    console.log('当前编辑表单数据:', editForm)
  } catch (error) {
    console.error('处理编辑操作时出错:', error)
    ElMessage.error('编辑操作失败，请重试')
  }
}

// 处理保存
const handleSave = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error('表单验证失败:', fields)
      return
    }

    try {
      console.log('保存前的表单数据:', editForm) // 添加日志
      // 构造提交的数据，确保所有必要字段都有值
      const submitData = {
        id: editForm.id || 0,
        shipmentsCode: editForm.shipmentsCode,
        shipmentsName: editForm.shipmentsName,
        saleCode: editForm.saleCode,
        custCode: editForm.custCode,
        custName: editForm.custName,
        shipmentsTime: editForm.shipmentsTime ? editForm.shipmentsTime + '.000Z' : '',
        receivingName: editForm.receivingName,
        phone: editForm.phone,
        receivingAddress: editForm.receivingAddress,
        speak: editForm.speak || '', // 修改为小写的speak
        state: editForm.state || 0
      }

      console.log('准备提交的数据:', submitData) // 添加日志

      // 确保所有必填字段都有值
      if (!submitData.shipmentsCode || !submitData.shipmentsName || !submitData.custCode || 
          !submitData.shipmentsTime || !submitData.receivingName || !submitData.phone || 
          !submitData.receivingAddress) {
        ElMessage.error('请填写所有必填字段')
        return
      }

      const url = editForm.id 
        ? '/api/ShipmentsModel/UpdateShipmentsModel'
        : '/api/ShipmentsModel/AddShipmentsModel'
      
      const res = await http.post(url, submitData)
      console.log('API响应:', res) // 添加日志
      if (res.status === true) {
        ElMessage.success(editForm.id ? '修改成功' : '添加成功')
        editDialogVisible.value = false
        getShipmentsList()
      } else {
        ElMessage.error(res.message || (editForm.id ? '修改失败' : '添加失败'))
      }
    } catch (error) {
      console.error(editForm.id ? '修改失败:' : '添加失败:', error)
      ElMessage.error(editForm.id ? '修改失败' : '添加失败')
    }
  })
}

// 处理编辑对话框关闭
const handleEditDialogClose = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  
  // 重置表单数据
  Object.assign(editForm, {
    id: '',
    shipmentsCode: '',
    shipmentsName: '',
    saleCode: '',
    custCode: '',
    custName: '',
    shipmentsTime: '',
    receivingName: '',
    phone: '',
    receivingAddress: '',
    speak: '',
    state: 0
  })
  
  // 重置自动生成开关为默认值
  autoGenerate.value = true
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return date.split('T')[0]
}

// 处理单个删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该发货通知单吗？', '提示', {
      type: 'warning'
    })
    
    const res = await http.get(`/api/ShipmentsModel/DeleteShipmentsModels?ids=${row.id}`)
    if (res.status === true) {
      ElMessage.success('删除成功')
      getShipmentsList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理批量删除
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的发货通知单')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个发货通知单吗？`, '提示', {
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id)
    const queryString = ids.join(',')
    const res = await http.get(`/api/ShipmentsModel/DeleteShipmentsModels?ids=${queryString}`)
    
    if (res.status === true) {
      ElMessage.success('批量删除成功')
      getShipmentsList()
    } else {
      ElMessage.error(res.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 处理客户选择
const handleCustomerSelect = (customer) => {
  editForm.custCode = customer.custCode
  editForm.custName = customer.custName
  customerSelectVisible.value = false
}

// 打开客户选择对话框
const openCustomerSelect = () => {
  customerSelectVisible.value = true
}

// 监听自动生成开关
watch(autoGenerate, (newVal) => {
  if (newVal && !editForm.id) {
    generateShipmentsCode()
  }
})

// 生成发货通知单编号
const generateShipmentsCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  editForm.shipmentsCode = `SN${year}${month}${day}${hours}${minutes}${seconds}`
}

// 初始化加载数据
onMounted(() => {
  getShipmentsList()
})

// 处理保存物料
const handleSaveMaterial = async () => {
  if (!materialFormRef.value) return

  try {
    await materialFormRef.value.validate()
    
    // 构造保存的数据，确保字段名称与数据库一致
    const saveData = {
      Id: materialForm.id || 0,
      MaterialCode: materialForm.materialCode,
      MaterialName: materialForm.materialName,
      Specification: materialForm.specification,
      Flats: materialForm.flats,
      FlatsMaterial: materialForm.flatsMaterial,
      IsLock: materialForm.isLock ? 1 : 0,
      SafetyStock: materialForm.safetyStock ? 1 : 0,
      Descs: materialForm.descs || ''
    }

    console.log('保存物料数据:', saveData)

    const url = materialForm.id
      ? '/api/MaterialProduct/UpdateMaterialProduct'
      : '/api/MaterialProduct/AddMaterialProduct'

    const res = await http.post(url, saveData)
    
    if (res.status === true) {
      ElMessage.success(materialForm.id ? '修改成功' : '添加成功')
      materialDialogVisible.value = false
      getMaterialList()
    } else {
      ElMessage.error(res.message || (materialForm.id ? '修改失败' : '添加失败'))
    }
  } catch (error) {
    console.error('保存物料失败:', error)
    ElMessage.error('保存失败，请检查表单')
  }
}

// 打开物料选择对话框
const openMaterialSelect = () => {
  materialSelectVisible.value = true
}

// 处理物料选择
const handleMaterialSelect = (material) => {
  materialForm.materialCode = material.materialCode
  materialForm.materialName = material.materialName
  materialForm.specification = material.specification
  materialForm.flats = material.flats
  materialForm.flatsMaterial = material.flatsMaterial
  materialSelectVisible.value = false
}

// 处理批量删除物料
const handleBatchDeleteMaterial = async () => {
  if (!selectedMaterials.value.length) {
    ElMessage.warning('请选择要删除的物料')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedMaterials.value.length} 个物料吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    const ids = selectedMaterials.value.map(item => item.id).join(',')
    const res = await http.get(`/api/MaterialProduct/DeleteMaterialProduct?id=${ids}`)
    
    if (res.status === true) {
      ElMessage.success('批量删除成功')
      getMaterialList()
    } else {
      ElMessage.error(res.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除物料失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}
</script>

<style lang="scss" scoped>
.shipments-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.table-operations {
  margin-bottom: 16px;
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-operations .el-button {
  margin-right: 8px;
}

.el-table {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-info {
  margin-right: 16px;
  color: #606266;
}

.pagination-select {
  display: flex;
  align-items: center;
  margin-right: 16px;
  color: #606266;
}

.pagination-select .el-button {
  padding: 0 4px;
  margin-left: 8px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-button--text) {
  padding: 0 4px;
}

:deep(.el-dropdown-menu__item) {
  padding: 5px 16px;
}

.shipment-form {
  padding: 20px;

  :deep(.el-form-item__label) {
    font-weight: normal;
    color: #606266;
  }

  :deep(.el-form-item__content) {
    flex: 1;
  }

  .code-input-container {
    display: flex;
    align-items: center;
    gap: 10px;

    .el-input {
      flex: 1;
    }

    .auto-switch {
      margin-left: 10px;
    }
  }

  .customer-input-container {
    display: flex;
    align-items: center;
    gap: 10px;

    .el-input {
      flex: 1;
    }

    .select-customer-btn {
      padding: 0 12px;
      height: 32px;
      border-radius: 0 4px 4px 0;
      margin-left: -1px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding-top: 20px;
}

:deep(.el-dialog) {
  border-radius: 8px;
  
  .el-dialog__header {
    margin: 0;
    padding: 20px;
    border-bottom: 1px solid #dcdfe6;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  .el-dialog__footer {
    padding: 10px 20px 20px;
    border-top: 1px solid #dcdfe6;
  }
}

:deep(.el-form-item.is-required) {
  .el-form-item__label::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

.material-section {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #dcdfe6;

  .material-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
      position: relative;
      padding-left: 12px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background-color: #409eff;
        border-radius: 2px;
      }
    }

    .material-toolbar {
      display: flex;
      gap: 10px;
    }
  }

  .el-table {
    margin-bottom: 20px;
    
    :deep(.el-table__header) {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
      }
    }

    :deep(.el-button--link) {
      padding: 2px 4px;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding-top: 20px;
  }
}

:deep(.el-tag) {
  min-width: 48px;
  text-align: center;
}

:deep(.el-switch) {
  --el-switch-on-color: #409eff;
}

.material-code-link {
  color: #409EFF;
  text-decoration: none;
  cursor: pointer;

  &:hover {
    color: #66b1ff;
    text-decoration: underline;
  }
}

.pagination-container {
  margin-top: 20px;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #fff;
  border-top: 1px solid #EBEEF5;

  .total-text {
    margin-right: 16px;
    color: #606266;
  }

  .page-size-selector {
    margin-right: 16px;
  }

  .custom-pagination {
    display: flex;
    align-items: center;
    gap: 8px;

    .page-btn {
      min-width: 32px;
      height: 32px;
      padding: 0 4px;
      margin: 0 4px;
      line-height: 30px;
      text-align: center;
      background: #fff;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      color: #606266;

      &:hover:not(:disabled) {
        color: #409EFF;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
      }

      &:disabled {
        color: #c0c4cc;
        cursor: not-allowed;
      }

      &.active {
        color: #fff;
        background-color: #409EFF;
        border-color: #409EFF;
      }
    }

    .page-numbers {
      display: flex;
      align-items: center;
    }
  }

  .page-jump {
    margin-left: 16px;
    display: flex;
    align-items: center;

    .text {
      margin: 0 4px;
      color: #606266;
    }

    .jump-input {
      width: 50px;
      margin: 0 4px;
    }
  }
}

.safety-stock-tag {
  width: 48px;
  text-align: center;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.material-input-container {
  display: flex;
  align-items: center;
  gap: 10px;

  .el-input {
    flex: 1;
  }

  .select-material-btn {
    padding: 0 12px;
    height: 32px;
    border-radius: 0 4px 4px 0;
    margin-left: -1px;
  }
}
</style>